<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 工具栏自定义组件 -->
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条数据</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import?type=user')"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="exportData"
          >导出</el-button>
          <el-button
            size="small"
            type="primary"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" type="index" align="center" />
          <el-table-column label="姓名" prop="username" align="center" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{ row }">
              <img
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="width: 80px; border-radius: 50%; padding: 10px"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" align="center" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formatEmployment"
            align="center"
          />
          <el-table-column label="部门" prop="departmentName" align="center" />
          <el-table-column label="入职时间" prop="timeOfEntry" align="center">
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" align="center">
            <template slot-scope="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <!-- <template v-slot="{ row }"> -->
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                :disabled="!checkPermission('POINT-USER-UPDATE')"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="deleteEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <AddEmployee :show-dialog.sync="showDialog" />
      <el-dialog :visible.sync="showCodeDialog" title="扫描二维码查看头像">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <AssignRole ref="AssignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [], // 员工数据列表
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      loading: false,
      showDialog: false, // 控制添加员工弹层
      showCodeDialog: false, // 控制二维码弹层
      showRoleDialog: false, // 控制角色权限弹层
      userId: '' // 点击对应角色的id
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取员工列表数据
    async getEmployeeList() {
      this.loading = true
      // 在响应拦截器已经拦截错误信息，所以以后请求不用try catch
      // 接口问题，404，没有数据 赋值请求地址前面多带了个空格 !!!
      const { total, rows } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    // 切换页数时间句柄
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      return (
        EmployeeEnum.hireType.find((item) => item.id === cellValue)?.value ||
        '未知'
      )
    },
    // 删除员工
    async deleteEmployee(id) {
      try {
        await this.$confirm('确定删除该员工吗？')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (err) {
        console.log(err)
      }
    },
    // 批量到处员工到Excel
    // 导出excel数据
    exportData() {
      //  做操作
      // 表头对应关系
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      // 懒加载
      import('@/vendor/Export2Excel').then(async(excel) => {
        const { rows } = await getEmployeeList({
          page: 1,
          size: 10
        })
        const data = this.formatJson(headers, rows)
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx',
          multiHeader, // 复杂表头
          merges // 合并选项
        })
      })
    },
    // 该方法负责将数组转化成二维数组, 并且根据 headers 表头的顺序
    // [{key1: val1, key2: val2}, {key1: val1, key2: val2}] => [[val1, val2], [val1, val2]]
    formatJson(headers, rows) {
      return rows.map((item) => {
        // Object.keys(headers) => ['姓名', ....]
        return Object.keys(headers).map((key) => {
          if (
            headers[key] === 'timeOfEntry' ||
            headers[key] === 'correctionTime'
          ) {
            return formatDate(item[headers[key]]) // 返回格式化之前的时间
          } else if (headers[key] === 'formOfEmployment') {
            var en = EmployeeEnum.hireType.find(
              (obj) => obj.id === item[headers[key]]
            )
            return en ? en.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    // 控制二维码弹层
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true
        // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    async editRole(id) {
      this.userId = id
      await this.$refs.AssignRole.getUserDetailById(id)
      this.showRoleDialog = true
    }
  }
}
</script>

<style>
</style>
